<?php
function myException($exception) {
	Helper_Common::log ( print_r ( func_get_args (), true ), 'api_err' );
	$result = array (
			'errcode' => 9999,
			'errmsg' => '服务器发生错误',
			'data' => array () 
	);
	// $this->logs("RESPONSE:".print_r($result,true));
	$appcalitonType = isset ( $_SERVER ['HTTP_ACCEPT'] ) ? trim ( $_SERVER ['HTTP_ACCEPT'] ) : '';
     echo json_encode ( $result );
	exit ();
}
set_exception_handler ( 'myException' );
set_error_handler ( 'myException' );
/**
 * 默认控制器
 */
class Controller_api extends Controller_Abstract {
	

	
	/**
	 * 客户端请求唯一码
	 * 
	 * @var string
	 */
	protected $_userAgent = '';

	/**
	 * 客户端代理ID
	 * 
	 * @var int
	 */
	protected $_appid = 0;
	protected $_appkey = '';
	protected $_packageid = 1;
	protected $appConfig = array ();
	protected $regKeyConfig = array (
			'notdefined' => 4 
	);
	protected $appErrCode = array (
			'0' => '操作成功' ,
	        '1001'=>'need sign',
	        '1002'=>'appid错误',
	        '1004'=>' need appid',
	        '1003'=>'加密错误',
	        '1005'=>'请求参数不完整',
	        '2001'=>'密码错误',
	        '2002'=>'验证码错误',
	        '2003'=>'密码和确认密码不一致',
	        '2004'=>'用户未找到',
	        '2005'=>'用户被锁定',
	        '2027'=>'今日红包已抽完，请明日再来',
	        '2028'=>'此功能尚未开启',
	        '2025'=>'红包金额尚未设置',
	        '2026'=>'今日抽奖机会已经用完，请明日再来',
	        '2029'=>'授权码不能为空',
	        '2030'=>'授权码错误',
	        '2031'=>'授权码过期',
	        '2033'=>'数据未找到',
	        '2034'=>'授权码已经使用',
	        '2035'=>'该用户已经授权',
	        '2037'=>'新闻未找到',
	        '2039'=>'文章未找到',
	        '2040'=>'您粘贴的不是微信新闻',
	        '2041'=>'code参数错误',
	        '2042'=>'url格式不正确',
	        '2043'=>'该手机号码已经注册,请返回登陆界面直接登陆',
	        '2044'=>'免费试用次数已经使用完，请输入授权码授权',
	        
	        
	);
	protected $requestData = array ();
	function _before_execute() {
	    $filename = Q::ini('app_config/ROOT_DIR').'/config/api.yaml';
		$this->appConfig = Helper_YAML::load($filename);
		
	    $this->_appid = $this->appConfig['appid'];
	    $this->_appkey = $this->appConfig['appkey'];
	    
	    //打包ID即代理ID
	    $this->_packageid =  ( isset ( $_SERVER ['HTTP_PACKAGEID'] ) ? trim ( $_SERVER ['HTTP_PACKAGEID'] ) : '1' );
	    
	}
	/**
	 * 记录API请求日志
	 * 
	 * @param string $mgs        	
	 */
	protected function logs($msg) {
		$action_log = trim ( $this->_context->action_name );
		Helper_Common::log ( $msg, $action_log );
	}
	
	/**
	 * 输出消息
	 *
	 * @param int $code
	 *        	错误码
	 * @param string $msg
	 *        	错误信息
	 * @param array $data
	 *        	输出数据
	 */
	protected function responseMsg($code, $data = array()) {
	    $msg = isset ( $this->appErrCode [$code] ) ? trim ( $this->appErrCode [$code] ) : '系统错误';
	    $result = array (
	            'errcode' => intval ( $code ),
	            'errmsg' => trim ( $msg ),
	            'data' => $data
	    );
	         $this->logs ( "RESPONSE:" . print_r ( $result, true ) );
	        $result = json_encode($result);
	        if(strpos($result, '{tel}') !== false){
	            $result = str_replace('{tel}', $this->requestData['username'], $result);
	        }
	        exit  ( $result );
	}

	
	/**
	 * 请求参数效验
	 * 
	 * @param array $questData
	 *        	当次请求需要效验的参数键
	 */
	protected function checkParamValid($questData) {
		if (! isset ( $questData ['sign'] ) || ! $questData ['sign']) {
			
			return 1001; // 未提交sign
		} else {
			$sign = strtolower ( trim ( $questData ['sign'] ) );
			unset ( $questData ['sign'] );
			$time = time ();

			if (! isset ( $questData ['appid'] ) || ! $questData ['appid']) {
				return 1004; // need appid
			} else if ($questData ['appid'] !== $this->_appid) {
				return 1012; // appid <> header appid
			} else {
				$appkey = $this->_appkey;
				ksort ( $questData, SORT_STRING );
				$makeSign = '';
				foreach ( $questData as $v ) {
					if (is_array ( $v )) {
						$makeSign .= $v [0];
					} else {
						$makeSign .= $v;
					}
				}				
				$makeSign .= $appkey;
				$this->logs ( "make string : {$makeSign},md5=" . md5 ( $makeSign ) );
				$makeSign = md5 ( $makeSign );
				Helper_Common::log($makeSign);
		
				if ($makeSign == $sign) {
					return 0;
				} else {
					return 1003; // sign 不等于
				}
			}
		}
	}
	/**
	 * 检测参数是否齐全
	 * 
	 * @param array $needParam        	
	 */
	protected function checkNeedParam($needParam) {	 
	$this->logs ( "REQUEST URL:{$_SERVER['REQUEST_URI']},HEADER=" . print_r ( $_SERVER, true ) . ",REQUEST " . $this->_context->action_name . " :" . print_r ( $_REQUEST, true ) );
		foreach ( $needParam as $v ) {

			if (! isset ( $_REQUEST [$v] )) {
				$this->logs ( 'need param:' . $v );
				$this->appErrCode [1005] .= ",need param {$v}";
				$this->responseMsg ( 1005 );
			} else {
				$this->requestData [$v] = str_replace ( '(null)', '', $_REQUEST [$v] );
			}
		}
		return true;
	}

	/*
	 * 初始化主页接口
	 */
	function actioninit(){
	    $needParam = array (
	            'appid',
	            'timeline',
	            'sign',
	    
	    );
	    $this->checkNeedParam ( $needParam );
	    $signCheck = $this->checkParamValid ( $this->requestData );
	    if ($signCheck !== 0) $this->responseMsg ( $signCheck );
	    $banner = array();
	    $host = Helper_Common::getRequestHost();
	    $initinfo = array(
	           
                       'ads_img'=>'http://'.$_SERVER['HTTP_HOST'].'/images/ads.png',
                       'mainurl'=>'http://www.baidu.com',
	                   'wehchat_id'=>'后台自定义',
	                   'isup'=>0
	            	  );
	    
	    $acct = Acct::find('id = ?',$this->getAgentId())->getOne();
	    $down = down::find('agent_id = ?',$this->getAgentId())->getOne();
	    if($acct->id() && $acct->isup ==1 ){//上架了
	        $mainurl = $acct->mainurl;
	    }
	    if($down->id() && $down->url  && $acct->isup ==0){//没上架
	        $mainurl = $down->url;
	    }
	    
	    if($acct->id()){
	        $initinfo['init_img'] = $acct->startimg;
	        $initinfo['ads_img'] = $acct->startimg;
	        $initinfo['wechat_id'] = $acct->wechat_id;
	        $initinfo['isup'] = $acct->isup;
	      
	    }
	    //国外ip
	    $ip = Helper_Common::get_ip();
	    $iplimit = new helper_iplimit();
	    if(!$iplimit->setup($ip) && $initinfo['isup'] == 1){//国外的ip并且已经上架了 
	        $initinfo['isup'] = 0;
	    }
	    if(!empty($mainurl))   $initinfo['mainurl']= $mainurl;
	    $this->responseMsg ( 0,$initinfo );
	}

	
	function getAgentId()
	{
	    if(isset($this->_packageid) && intval($this->_packageid))
	    {
	        return intval($this->_packageid);
	    }else{
	        return 2;
	    }
	}
	
	function actionmaininfo(){
	    $needParam = array (
	            'appid',
	            'timeline',
	            'sign',
	             
	    );
	    $this->checkNeedParam ( $needParam );
	    $signCheck = $this->checkParamValid ( $this->requestData );
	    if ($signCheck !== 0) $this->responseMsg ( $signCheck );
	    $down = down::find('agent_id = ?',$this->getAgentId())->setColumns('id,title,mainimg,img1,buttontext1,img2,buttontext2,img3,buttontext3,maincontent')->asArray()->getOne();
	    $down['url1']= 'http://baijl.dabaibenben.com/webmain/rule1/id/'.$down['id'];
	    $down['url2']= 'http://baijl.dabaibenben.com/webmain/rule2/id/'.$down['id'];
	    $down['url3']= 'http://baijl.dabaibenben.com/webmain/rule3/id/'.$down['id'];
	    $data = $down;
	    $this->responseMsg(0,$data);
	}
}





